package com.winning.sjzc.sjypz.utils;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @ClassName DynamicDataSourceConfig
 * @Description TODO
 * @Author WJX
 * @Date 2019/8/15 18:48
 **/
public class DynamicDataSourceConfig {

    public DynamicDataSourceConfig(String driverClassName,String jdbcurl,String username,String password){
        this.driverClassName = driverClassName;
        this.url = jdbcurl;
        this.username = username;
        this.password = password;
    }

    private String url;
    private String username;
    private String password;
    private String driverClassName;
    /**
     * 初始化时建立物理连接的个数
     */
    private int initialSize = 5;
    /**
     *最小连接池数量
     */
    private int minIdle = 5;
    /**
     * 最大连接池数量
     */
    private int maxActive = 100;
    /**
     * 获取连接时最大等待时间，单位毫秒。
     */
    private long maxWait = 10000;
    /**
     * 间隔多久进行一次检测，检测需要关闭的空闲连接
     */
    private long timeBetweenEvictionRunsMillis = 60000;
    /**
     * 一个连接在池中最小生存的时间
     */
    private long minEvictableIdleTimeMillis = 300000;
    /**
     * 开启池的prepared statement 池功能
     */
    private boolean poolPreparedStatements = true;

    /**
     * 获取到数据源
     * @return
     * @throws SQLException
     */
    public DataSource getDataSource() throws SQLException {
        DruidDataSource druid = new DruidDataSource();
        // 配置基本属性
        druid.setDriverClassName(driverClassName);
        druid.setUsername(username);
        druid.setPassword(password);
        druid.setUrl(url);
        //初始化时建立物理连接的个数
        druid.setInitialSize(initialSize);
        //最大连接池数量
        druid.setMaxActive(maxActive);
        //最小连接池数量
        druid.setMinIdle(minIdle);
        //获取连接时最大等待时间，单位毫秒。
        druid.setMaxWait(maxWait);
        //间隔多久进行一次检测，检测需要关闭的空闲连接
        druid.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        //一个连接在池中最小生存的时间
        druid.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        return druid;
    }

    /**
     * 通过数据源获取到连接
     * @return
     * @throws SQLException
     */
    public Connection druidConnection() throws SQLException {
        Connection con = null;
        con = getDataSource().getConnection();
        return con;
    }


    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }
}
